package com.core.springSecurity.service;


import com.common.utils.Constants;
import com.common.ErrorCodeEnum;
import com.common.exception.BusinessException;
import com.common.redis.RedisCache;
import com.common.utils.StringUtils;
import com.core.asyncManager.AsyncManager;
import com.core.asyncManager.factory.AsyncFactory;
import com.core.springSecurity.common.FingerprintUtils;
import com.core.springSecurity.model.LoginUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 令牌服务
 * @author cat*/
@Slf4j
@Component
public class TokenService {
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    /** 令牌自定义标识 */
    private static String header;
    /**令牌自定义标识*/
    @Value("${token.header:Authorization}")
    public void setHeader(String header) {
        TokenService.header = header;
    }

    public static String getHeader() {
        return TokenService.header;
    }

    /** 令牌秘钥*/
    @Value("${token.secret:abcdefghijklmnopqrstuvwxyz}")
    private String secret;

    /** 令牌有效期（默认180分钟）*/
    @Value("${token.expireTime:180}")
    private int expireTime;

    @Resource
    private RedisCache redisCache;
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserDetails getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String loginKey = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(loginKey);
            return redisCache.getCacheObject(userKey);
        }
        return null;
    }


    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUserDetails loginUserDetails) {
        if (StringUtils.isNotNull(loginUserDetails) && StringUtils.isNotEmpty(loginUserDetails.getLoginKey())) {
            refreshToken(loginUserDetails);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String loginKey) {
        if (StringUtils.isNotEmpty(loginKey)) {
            String userKey = getTokenKey(loginKey);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUserDetails 用户信息
     * @return 令牌
     */
    public String createToken(LoginUserDetails loginUserDetails) {
        //更换key产生方式，防止反复登录出现多个同一个账户token
        String loginKey = loginUserDetails.getUser().getSysUserId().toString()+ FingerprintUtils.getFingerprintDeviceID();//IdUtils.fastUUID();
        loginUserDetails.setLoginKey(loginKey);
        refreshToken(loginUserDetails);
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(Constants.LOGIN_USER_KEY, loginKey);
        return createToken(claims);
    }

    /**
     * 创建令牌
     *
     * @param loginUserDetails 苗木用户信息
     * @return 令牌
     */
    public String createNurseryToken(LoginUserDetails loginUserDetails) {
        //更换key产生方式，防止反复登录出现多个同一个账户token
        String loginKey = "";//loginUserDetails.getUserBaseInfo().getUserId().toString()+ FingerprintUtils.getFingerprintDeviceID();//IdUtils.fastUUID();
        loginUserDetails.setLoginKey(loginKey);
        refreshNurseryToken(loginUserDetails);
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(Constants.LOGIN_USER_KEY, loginKey);
        return createToken(claims);
    }


    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUserDetails 登录信息
     */
    public void verifyToken(LoginUserDetails loginUserDetails) {
        long expireTime = loginUserDetails.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUserDetails);
        }
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUserDetails 登录信息
     */
    public void verifyNurseryToken(LoginUserDetails loginUserDetails) {
        long expireTime = loginUserDetails.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshNurseryToken(loginUserDetails);
        }
    }
    /**
     * 刷新令牌有效期
     *
     * @param loginUserDetails 登录信息
     */
    public void refreshToken(LoginUserDetails loginUserDetails) {
        loginUserDetails.setLoginTime(System.currentTimeMillis());
        loginUserDetails.setExpireTime(loginUserDetails.getLoginTime() + expireTime * Constants.MINUTE_MILLIS);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUserDetails.getLoginKey());
        //创建异步任务把记录存储到终端管理服务
        AsyncManager.me().execute(AsyncFactory.updateTerminal(loginUserDetails));

        redisCache.setCacheObject(userKey, loginUserDetails, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUserDetails 苗木登录信息
     */
    public void refreshNurseryToken(LoginUserDetails loginUserDetails) {
        loginUserDetails.setLoginTime(System.currentTimeMillis());
        loginUserDetails.setExpireTime(loginUserDetails.getLoginTime() + expireTime * Constants.MINUTE_MILLIS);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUserDetails.getLoginKey());
        //创建异步任务把记录存储到终端管理服务
        AsyncManager.me().execute(AsyncFactory.updateTerminal(loginUserDetails));

        redisCache.setCacheObject(userKey, loginUserDetails, expireTime, TimeUnit.MINUTES);
    }


//    /**
//     * 设置用户代理信息
//     *
//     * @param loginUser 登录信息
//     */
//    public void setUserAgent(LoginUser loginUser)
//    {
//        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
//        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
//        loginUser.setIpaddr(ip);
//        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
//        loginUser.setBrowser(userAgent.getBrowser().getName());
//        loginUser.setOs(userAgent.getOperatingSystem().getName());
//    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token ;
        try {
            token = Jwts.builder()
                    .setClaims(claims)
                    .signWith(SignatureAlgorithm.HS512, secret).compact();
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.TOKEN_CREATE_FAILED);
        }
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        Claims claims ;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.TOKEN_FAILED);
        }
        return claims;
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request 请求体
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
